#!/bin/sh

# shellcheck disable=SC1091
. /usr/sbin/balena-config-vars

# Handle apps.json existence
# Keep this before computing SUPERVISOR_CONTAINER_IMAGE_ID
APPSJSON=/mnt/data/apps.json
if [ ! -f "$APPSJSON" ]; then
    if [ -d "$APPSJSON" ]; then
        rm -rf "$APPSJSON"
        balena rm -f balena_supervisor || true
        echo '{}' > "$APPSJSON"
    elif [ ! -e "$APPSJSON" ]; then
        echo '{}' > "$APPSJSON"
    fi
fi

SUPERVISOR_IMAGE_ID=$(balena inspect --format='{{.Id}}' "$SUPERVISOR_IMAGE")
SUPERVISOR_CONTAINER_IMAGE_ID=$(balena inspect --format='{{.Image}}' balena_supervisor || echo "")

# If custom CA exists populate the NODE_EXTRA_CA_CERTS env variable as node ignores the system-wide CA bundle
BALENA_ROOT_CA_FILE="/usr/share/ca-certificates/balena/balenaRootCA.crt"
if [ -f "${BALENA_ROOT_CA_FILE}" ]; then
    NODE_EXTRA_CA_CERTS="/mnt/root/${BALENA_ROOT_CA_FILE}"
fi

hasValueChanged() {
    KEY="$1"
    NEW_VALUE="$2"
    COLLECTION="$3"
    CURRENT_VALUE=$(echo "$COLLECTION" | jq -r ".$KEY")

    if [ "$CURRENT_VALUE" != "$NEW_VALUE" ];then
        echo "$KEY has changed!"
    else
        return 1
    fi
}

configIsUnchanged() {

    SUPERVISOR_CONTAINER_ENV_JSON="$(balena inspect balena_supervisor | jq '.[0].Config.Env | map(.| { (.[0:index("=")]): .[index("=")+1:] }) | add')"

    if hasValueChanged "BOOT_MOUNTPOINT"       "$BOOT_MOUNTPOINT" "$SUPERVISOR_CONTAINER_ENV_JSON" || \
    hasValueChanged "MIXPANEL_TOKEN"        "$MIXPANEL_TOKEN" "$SUPERVISOR_CONTAINER_ENV_JSON" || \
    hasValueChanged "DELTA_ENDPOINT"        "$DELTA_ENDPOINT" "$SUPERVISOR_CONTAINER_ENV_JSON" || \
    hasValueChanged "LED_FILE"              "${LED_FILE}" "$SUPERVISOR_CONTAINER_ENV_JSON" || \
    hasValueChanged "LISTEN_PORT"           "$LISTEN_PORT" "$SUPERVISOR_CONTAINER_ENV_JSON" || \
    hasValueChanged "NODE_EXTRA_CA_CERTS"   "$NODE_EXTRA_CA_CERTS" "$SUPERVISOR_CONTAINER_ENV_JSON" || \
    hasValueChanged "SUPERVISOR_IMAGE"      "${SUPERVISOR_IMAGE}" "$SUPERVISOR_CONTAINER_ENV_JSON"; then
        echo "Container config has changed!"
        return 1
    else
        echo "Container config has not changed"
        return 0
    fi
}

runSupervisor() {
    balena rm --force balena_supervisor resin_supervisor 2>/dev/null || true
    balena run --privileged --name balena_supervisor \
        --restart=always \
        --net=host \
        --cidenv=SUPERVISOR_CONTAINER_ID \
        --mount type=bind,source=/var/run/balena-engine.sock,target=/var/run/balena-engine.sock \
        --mount type=bind,source="$CONFIG_PATH",target=/boot/config.json \
        --mount type=bind,source=/mnt/data/apps.json,target=/boot/apps.json \
        --mount type=bind,source=/resin-data/balena-supervisor,target=/data \
        --mount type=bind,source=/proc/net/fib_trie,target=/mnt/fib_trie \
        --mount type=bind,source=/var/log/supervisor-log,target=/var/log \
        --mount type=bind,source=/etc/ssl/certs,target=/etc/ssl/certs,readonly \
        --mount type=bind,source=/usr/share/ca-certificates,target=/usr/share/ca-certificates,readonly \
        --mount type=bind,source=/,target=/mnt/root \
        -e DOCKER_ROOT=/mnt/root/var/lib/docker \
        -e DOCKER_SOCKET=/var/run/balena-engine.sock \
        -e "BOOT_MOUNTPOINT=$BALENA_BOOT_MOUNTPOINT" \
        -e "MIXPANEL_TOKEN=$MIXPANEL_TOKEN" \
        -e "DELTA_ENDPOINT=$DELTA_ENDPOINT" \
        -e "LED_FILE=${LED_FILE}" \
        -e "LISTEN_PORT=$LISTEN_PORT" \
        -e "NODE_EXTRA_CA_CERTS=${NODE_EXTRA_CA_CERTS}" \
        -e "SUPERVISOR_IMAGE=${SUPERVISOR_IMAGE}" \
        "${SUPERVISOR_IMAGE}"
}

if [ ! -d "/resin-data/balena-supervisor" ]; then
	mkdir -p "/resin-data/balena-supervisor"
fi
if [ ! -d "/var/log/supervisor-log" ]; then
    mkdir -p "/var/log/supervisor-log"
fi

if [ -z "$SUPERVISOR_IMAGE_ID" ]; then
    # No supervisor image exists on the device, try to pull it
    systemctl start update-balena-supervisor
elif [ "$SUPERVISOR_IMAGE_ID" = "$SUPERVISOR_CONTAINER_IMAGE_ID" ] && configIsUnchanged; then
    # Supervisor image exists, and the current supervisor container is created from
    balena start --attach balena_supervisor
else
    # No supervisor container exists or there's a different supervisor image to run
    runSupervisor
fi
